#include "stdafx.h"
#include "aviprocessor.h"

unsigned __stdcall processImages( void *g/*vthreadarglist*//*Threadarglist *threadarglist*/) 
{
// 	Threadarglist *threadarglist = reinterpret_cast<Threadarglist *>(vthreadarglist);
// 	AviProcessor *proc= reinterpret_cast<AviProcessor *>(threadarglist->g);
	AviProcessor *proc= reinterpret_cast<AviProcessor *>(g);

	while (!proc->isStopped()) 
	{

		if(cvGrabFrame(proc->capture))
		{

			proc->img=cvRetrieveFrame(proc->capture);           

			// calling the process function
			if (proc->callingProcess())
			{
				Sleep(proc->getDelay());
				proc->process(proc->img, proc->energy, proc->energydiff, proc->mutualinfo, proc->nmutualinfo);
				//cvWriteFrame(proc->m_pVideoWriter, proc->img);
				if(cvWriteFrame(proc->m_pVideoWriter, proc->img) == 0)
				{
					AfxMessageBox(_T("Can not write to files"));
					//return;
				}
			}
			else
				Sleep(proc->getDelay());

			// displays image and frame number
			if (proc->isDisplayed()) 
			{

// 				CvScalar sc;
// 				char text[50];
// 				sprintf(text,"Frame #%6d",proc->getFrameNumber());
// 
// 				sc= cvGet2D(proc->img,20,20);
// 				if (sc.val[1]>128) 
// 					cvPutText(proc->img, text, cvPoint(20,20), &(proc->font), cvScalar(0,0,0));
// 				else
// 					cvPutText(proc->img, text, cvPoint(20,20), &(proc->font), cvScalar(255,255,255));


				//cvMoveWindow("Image (AviProcesor)", 300, 100);
				cvShowImage( "Image (AviProcessor)", proc->img );
				HWND hWnd= (HWND)cvGetWindowHandle("Image (AviProcessor)");
				::SendMessage(hWnd,WM_PAINT,NULL,NULL); // force the window to repaint
			}

			// increment frame number
			//*(threadarglist->pfreamno) = proc->getFrameNumber();
			*proc->frameno = proc->getFrameNumber();
			proc->incFrameNumber();
			//UpdateData(true);

		} else 
		{

			proc->stopIt();
		}
	}

    _endthreadex( 0 );
	return 0;
}
